package com.gjxblog.consumer;

import com.gjxblog.entity.Order;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;


/**
 * @author gjx
 * @version v1.0
 * @Description  springboot 整合 amqp
 * @date 2019/7/5 15:47
 */
@Component
@Slf4j
public class RabbitConsumer {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue-1",durable ="true"),
            exchange = @Exchange(value = "exchange-1",durable = "true",type =ExchangeTypes.TOPIC),
            key = "springboot.*"
    ))
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws IOException {
       log.info("message is :" +message.getPayload());

       Long amqp_deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
       log.info("amqp_deliveryTag is {}",amqp_deliveryTag);

        //手动ack
       channel.basicAck(amqp_deliveryTag,false);
    }


    /**
     * spring.rabbitmq.listener.order.queue.name=queue-2
     * spring.rabbitmq.listener.order.queue.durable=true
     * spring.rabbitmq.listener.order.exchange.name=exchange-2
     * spring.rabbitmq.listener.order.exchange.durable=true
     * spring.rabbitmq.listener.order.exchange.type=topic
     * spring.rabbitmq.listener.order.exchange.key=springboot.*
     * @param order
     * @param headers
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${spring.rabbitmq.listener.order.queue.name}",durable = "${spring.rabbitmq.listener.order.queue.durable}"),
            exchange = @Exchange(value = "${spring.rabbitmq.listener.order.exchange.name}",durable = "${spring.rabbitmq.listener.order.exchange.durable}",type = "${spring.rabbitmq.listener.order.exchange.type}"),
            key = "${spring.rabbitmq.listener.order.exchange.key}"
    ))
    @RabbitHandler
    public void onMessage(@Payload Order order, @Headers Map headers,Channel channel) throws IOException {
        log.info("order is :" +order.getName());

        Long amqp_deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);

        channel.basicAck(amqp_deliveryTag,false);
    }
}
